/****************************************************************************
**
** Copyright (C) 2009-2010 Mist Poryvaev.
** All rights reserved.
** Contact: Mist Poryvaev (mist.poryvaev@gmail.com)
**
** This file is part of the RailWorm project.
**
****************************************************************************/

#include "setupproxy.h"
#include "ui_setupproxy.h"

QSettings SetupProxySettings("railworm.ini", QSettings::IniFormat);

SetupProxy * SetupProxy::g_Instance = 0;

SetupProxy * SetupProxy::i() {
	if (g_Instance == 0) {
		g_Instance = new SetupProxy();
	}
	return g_Instance;
}

SetupProxy::SetupProxy(QWidget *parent) :
    QDialog(parent),
	ui(new Ui::SetupProxy) {

	ui->setupUi(this);
	ui->formLayout->setSizeConstraint(QLayout::SetFixedSize);

	m_SavedAddress = SetupProxySettings.value("SetupProxy/Address", "").toString();
	m_SavedPort = SetupProxySettings.value("SetupProxy/Port", "").toString();
	m_SavedUseProxy = SetupProxySettings.value("SetupProxy/UseProxy", false).toBool();

	ui->Address->setText(m_SavedAddress);
	ui->Port->setText(m_SavedPort);
	ui->UseProxy->setChecked(m_SavedUseProxy);
	ui->UseNoProxy->setChecked(!m_SavedUseProxy);
	ui->Address->setEnabled(m_SavedUseProxy);
	ui->Port->setEnabled(m_SavedUseProxy);
}

SetupProxy::~SetupProxy() {
    delete ui;
}

void SetupProxy::showEvent(QShowEvent * se) {
	m_SavedAddress = ui->Address->text();
	m_SavedPort = ui->Address->text();
	m_SavedUseProxy = ui->UseProxy->isChecked();
}

void SetupProxy::on_buttonBox_accepted() {
	m_SavedAddress = ui->Address->text();
	m_SavedPort = ui->Port->text();
	m_SavedUseProxy = ui->UseProxy->isChecked();
	if (m_SavedUseProxy) {
		emit ProxyChanged(m_SavedAddress, m_SavedPort);
	}
	else {
		emit ProxyChanged("", "");
	}
	SetupProxySettings.setValue("SetupProxy/Address", m_SavedAddress);
	SetupProxySettings.setValue("SetupProxy/Port", m_SavedPort);
	SetupProxySettings.setValue("SetupProxy/UseProxy", m_SavedUseProxy);
}

void SetupProxy::on_buttonBox_rejected() {
	ui->Address->setText(m_SavedAddress);
	ui->Port->setText(m_SavedPort);
	ui->UseProxy->setChecked(m_SavedUseProxy);
	ui->UseNoProxy->setChecked(!m_SavedUseProxy);

	if (m_SavedUseProxy) {
		emit ProxyChanged(m_SavedAddress, m_SavedPort);
	}
	else {
		emit ProxyChanged("", "");
	}
}

void SetupProxy::on_UseNoProxy_toggled(bool checked) {
	if (checked) {
		ui->UseProxy->setChecked(false);
		ui->Address->setEnabled(false);
		ui->Port->setEnabled(false);
	}
}

void SetupProxy::on_UseProxy_toggled(bool checked) {
	if (checked) {
		ui->UseNoProxy->setChecked(false);
		ui->Address->setEnabled(true);
		ui->Port->setEnabled(true);
	}
}
